/**
 * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.member.web;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import oracle.jdbc.driver.HAManager;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.member.entity.Member;
import com.jeeplus.modules.member.service.MemberService;

/**
 * 用户表Controller
 *
 * @author zhych
 * @version 2021-08-24
 */
@RestController
@RequestMapping(value = "/member/member")
public class MemberController extends BaseController {

    @Autowired
    private MemberService memberService;

    @ModelAttribute
    public Member get(@RequestParam(required = false) String id) {
        Member entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = memberService.get(id);
        }
        if (entity == null) {
            entity = new Member();
        }
        return entity;
    }

    /**
     * 用户表列表数据
     */
    @RequiresPermissions("member:member:list")
    @GetMapping("list")
    public AjaxJson list(Member member, HttpServletRequest request, HttpServletResponse response) {
        Page<Member> page = memberService.findPage(new Page<Member>(request, response), member);
        return AjaxJson.success().put("page", page);
    }

    /**
     * 根据Id获取用户表数据
     */
    @RequiresPermissions(value = {"member:member:view", "member:member:add", "member:member:edit"}, logical = Logical.OR)
    @GetMapping("queryById")
    public AjaxJson queryById(Member member) {
        return AjaxJson.success().put("member", member);
    }

    /**
     * 保存用户表
     */
    @RequiresPermissions(value = {"member:member:add", "member:member:edit"}, logical = Logical.OR)
    @PostMapping("save")
    public AjaxJson save(Member member, Model model) throws Exception {
        /**
         * 后台hibernate-validation插件校验
         */
        String errMsg = beanValidator(member);
        if (StringUtils.isNotBlank(errMsg)) {
            return AjaxJson.error(errMsg);
        }
        //新增或编辑表单保存
        memberService.save(member);//保存
        return AjaxJson.success("保存用户表成功");
    }


    /**
     * 批量删除用户表
     */
    @RequiresPermissions("member:member:del")
    @DeleteMapping("delete")
    public AjaxJson delete(String ids) {
        String idArray[] = ids.split(",");
        for (String id : idArray) {
            memberService.delete(new Member(id));
        }
        return AjaxJson.success("删除用户表成功");
    }

    /**
     * 导出excel文件
     */
    @RequiresPermissions("member:member:export")
    @GetMapping("export")
    public AjaxJson exportFile(Member member, HttpServletRequest request, HttpServletResponse response) {
        try {
            String fileName = "用户表" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
            Page<Member> page = memberService.findPage(new Page<Member>(request, response, -1), member);
            new ExportExcel("用户表", Member.class).setDataList(page.getList()).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            return AjaxJson.error("导出用户表记录失败！失败信息：" + e.getMessage());
        }
    }

    /**
     * 导入Excel数据
     */
    @RequiresPermissions("member:member:import")
    @PostMapping("import")
    public AjaxJson importFile(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
        try {
            int successNum = 0;
            int failureNum = 0;
            StringBuilder failureMsg = new StringBuilder();
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<Member> list = ei.getDataList(Member.class);
            for (Member member : list) {
                try {
                    memberService.save(member);
                    successNum++;
                } catch (ConstraintViolationException ex) {
                    failureNum++;
                } catch (Exception ex) {
                    failureNum++;
                }
            }
            if (failureNum > 0) {
                failureMsg.insert(0, "，失败 " + failureNum + " 条用户表记录。");
            }
            return AjaxJson.success("已成功导入 " + successNum + " 条用户表记录" + failureMsg);
        } catch (Exception e) {
            return AjaxJson.error("导入用户表失败！失败信息：" + e.getMessage());
        }
    }

    /**
     * 下载导入用户表数据模板
     */
    @RequiresPermissions("member:member:import")
    @GetMapping("import/template")
    public AjaxJson importFileTemplate(HttpServletResponse response) {
        try {
            String fileName = "用户表数据导入模板.xlsx";
            List<Member> list = Lists.newArrayList();
            new ExportExcel("用户表数据", Member.class, 1).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            return AjaxJson.error("导入模板下载失败！失败信息：" + e.getMessage());
        }
    }


    /**
     * 获取用户推荐的下级关系
     * @param uid 推荐人的id
     * @return 推荐的用户列表
     */
    @RequestMapping("mySonList")
    public AjaxJson mySonList(String uid) {
        Member member = new Member();
        member.setInvite(new Member(uid));
        List<Member> list = memberService.findList(member);
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (Member member1 : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("nickname", member1.getNickname());
            map.put("mobile", member1.getMobile());
            map.put("gender", StringUtils.isBlank(member1.getGender()) ? "" : member1.getGender());
            map.put("createDate", ymdHms(member1.getCreateDate()));
            mapList.add(map);
        }
        return AjaxJson.success().put("data", mapList);
    }

    /**
     * 更改用户角色
     * @param id 用户id
     * @return 状态
     */
    @RequestMapping("change")
    public AjaxJson change(String id) {
        Member member = memberService.get(id);
        member.setUserType("2");
        memberService.save(member);
        return AjaxJson.success("设置成功");
    }
}